package com.dsd.datav.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.dsd.datav.dto.LoginUser;

import java.util.Date;

/**
 * @author Administrator
 * @Title: RedisUtil
 * @ProjectName cms
 * @Description: TODO
 * @date 2022/3/2 00022022/3/2 0002
 */
public class TokenUtil {
  private static final long EXPIRE_TIME= 15*60*1000;
  private static final String TOKEN_SECRET="dsd123456";  //密钥盐
  /**
   * 签名生成
   * @param user
   * @return
   */
  public static String sign(LoginUser user) {
    String token = null;
    try {
      Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
      token = JWT.create()//创建jwtCreator实例
              .withIssuer("dsd")//签发人
              .withClaim("id", user.getId()) //Payload负载
              .withExpiresAt(expiresAt)//过期时间
              .sign(Algorithm.HMAC256(TOKEN_SECRET)); // 使用了HMAC256加密算法 加盐加密。
    } catch (Exception e){
      e.printStackTrace();
    }
    return token;
  }

  /**
   * 签名验证
   * @param token
   * @return
   */
  public static boolean verify(String token){
    try {
      JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("dsd").build();
      DecodedJWT jwt = verifier.verify(token);
      System.out.println("认证通过：");
      System.out.println("issuer: " + jwt.getIssuer());
      System.out.println("username: " + jwt.getClaim("username").asString());
      System.out.println("过期时间：      " + jwt.getExpiresAt());
      return true;
    } catch (Exception e){
      return false;
    }
  }



}
